package com.ppo.test.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MultiThreadFutureTask implements Callable<String> {

	String name;
	String bean; 
	
	public MultiThreadFutureTask(String name, String bean) {
		super();
		this.name = name;
		this.bean = bean;
	}



	public String call() throws Exception {
		String name = this.name;
		System.out.println("NAME:"+name);
		
		if(name.indexOf("2")!=-1) {
			Thread.sleep(10000);
		}
		
		return new java.util.Date().toString()+" " + this.bean;
	}
	
	
	

	public static void main(String[] argv) {

		final int MAX_DURATION_IN_SECONDS = 2;
		final int THREADS_COUNT = 10;

		MultiThreadFutureTask mtf1 = new MultiThreadFutureTask("T1", "longueur_chaine1");
		MultiThreadFutureTask mtf2 = new MultiThreadFutureTask("T2", "longueur_chaine2_longueur_chaine2");
		MultiThreadFutureTask mtf3 = new MultiThreadFutureTask("T3", "longueur_chaine3_longueur_chaine3_longueur_chaine3");

		FutureTask<String> task1 = new FutureTask<String>(mtf1);
		FutureTask<String> task2 = new FutureTask<String>(mtf2);
		FutureTask<String> task3 = new FutureTask<String>(mtf3);

		ExecutorService executorService = Executors.newFixedThreadPool(THREADS_COUNT);

		executorService.execute(task1);
		executorService.execute(task2);
		executorService.execute(task3);

		// executorService.shutdown();

		// try {
		// executorService.awaitTermination(MAX_DURATION_IN_SECONDS,
		// TimeUnit.SECONDS);
		// } catch (InterruptedException e) {
		// System.out.println("Error in concurrent threads");
		// e.printStackTrace();
		// }
		
		
		System.out.println(printValue(task1,MAX_DURATION_IN_SECONDS));
		System.out.println(printValue(task2,MAX_DURATION_IN_SECONDS));
		System.out.println(printValue(task3,MAX_DURATION_IN_SECONDS));

		
	}



	static String printValue(FutureTask<String> task, int MAX_DURATION_IN_SECONDS) {
		String value=null;
		
		try {
			 value = task.get(MAX_DURATION_IN_SECONDS, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
			task.cancel(true);
		}
		return value;
	}


}
